﻿namespace MicroCloud.Utils
{
    /// <summary>
    /// 雪花ID生成器
    /// </summary>
    public class SnowflakeIdGenerator
    {
        #region "属性"
        #region "获取或设置 机器ID"
        private static long _WorkerId = 1;
        /// <summary>
        /// 获取或设置 机器ID
        /// </summary>
        public static long WorkerId
        {
            get { return _WorkerId; }
            set
            {
                var workerId = value;
                if (workerId > MaxWorkerId || workerId < 0)
                {
                    //throw new Exception(string.Format("worker Id can't be greater than {0} or less than 0 ", workerId));
                    throw new System.Exception($"机器ID值必须介于 0 和 {MaxWorkerId} 之间");
                }
                _WorkerId = workerId;
            }
        }
        #endregion
        #region "获取或设置 开始时间戳 (毫秒，默认：2020-01-01)，这是一个避免重复的随机量，自行设定不要大于当前时间戳"
        private static long _Twepoch = 1577808000000L;
        /// <summary>
        /// 获取或设置 开始时间戳 (毫秒，默认：2020-01-01)
        /// ，这是一个避免重复的随机量，自行设定不要大于当前时间戳
        /// </summary>
        public static long Twepoch
        {
            get { return _Twepoch; }
            set
            {
                var twepoch = value;
                long timestamp = TimeGen();
                while (twepoch > timestamp)
                {
                    throw new System.Exception($"自行设定不要大于当前时间戳 {timestamp}(总毫秒数)");
                }
                _Twepoch = twepoch;
            }
        }
        #endregion
        #region "获取 最大机器ID"
        /// <summary>
        /// 获取 最大机器ID
        /// </summary>
        public static long MaxWorkerId { get { return -1L ^ -1L << WorkerIdBits; } }
        #endregion
        #region "获取 一毫秒内可以产生计数，如果达到该值则等到下一毫秒再进行生成"
        /// <summary>
        /// 获取 一毫秒内可以产生计数，如果达到该值则等到下一毫秒再进行生成
        /// </summary>
        public static long SequenceMask { get { return -1L ^ -1L << SequenceBits; } }
        #endregion

        #region "获取 机器码字节数。8个字节用来保存机器码(定义为Long类型会出现，最大偏移64位，所以左移64位没有意义)"
        /// <summary>
        /// 获取 机器码字节数。8个字节用来保存机器码(定义为Long类型会出现，最大偏移64位，所以左移64位没有意义)
        /// </summary>
        private static int WorkerIdBits => 8;
        #endregion
        #region "获取 计数器字节数，10个字节用来保存计数码"
        /// <summary>
        /// 获取 计数器字节数，10个字节用来保存计数码
        /// </summary>
        private static int SequenceBits => 10;
        #endregion
        #region "获取 机器码数据左移位数，就是后面计数器占用的位数"
        /// <summary>
        /// 获取 机器码数据左移位数，就是后面计数器占用的位数
        /// </summary>
        private static int WorkerIdShift { get { return SequenceBits; } }
        #endregion
        #region "获取 时间戳左移动位数就是机器码和计数器总字节数"
        /// <summary>
        /// 获取 时间戳左移动位数就是机器码和计数器总字节数
        /// (时间截向左移14位：机器码字节数+计数器字节数)
        /// </summary>
        private static int TimestampLeftShift { get { return SequenceBits + WorkerIdBits; } }
        #endregion
        #region "获取或设置 最后时间戳"
        /// <summary>
        /// 获取或设置 最后时间戳
        /// </summary>
        private static long LastTimestamp { get; set; } = -1L;
        #endregion
        #region "获取或设置 序列计数器"
        /// <summary>
        /// 获取或设置 序列计数器
        /// </summary>
        private static long Sequence { get; set; } = 0L;
        #endregion

        #region "获取或设置 线程锁对象"
        /// <summary>
        /// 获取或设置 线程锁对象
        /// </summary>
        private static object Locker { get; set; } = new object();
        #endregion

        #endregion

        #region "构造函数-私有"
        #region "初始化一个雪花ID生成器的新实例"
        /// <summary>
        /// 初始化一个雪花ID生成器的新实例
        /// </summary>
        private SnowflakeIdGenerator()
        { }
        #endregion

        #endregion

        #region "方法"
        #region "生成一个新的雪花ID"
        /// <summary>
        /// 生成一个新的雪花ID
        /// </summary>
        /// <returns>标准long类型雪花ID</returns>
        [MethodImpl(MethodImplOptions.Synchronized)]
        public static long NewId()
        {
            //异步情况下，使用Lock确保产生唯一ID
            lock (Locker)
            {
                long timestamp = TimeGen();
                if (LastTimestamp == timestamp)
                {
                    //同一毫秒中生成ID
                    Sequence = Sequence + 1 & SequenceMask; //用&运算计算该毫秒内产生的计数是否已经到达上限
                    if (Sequence == 0)
                    {
                        //一毫秒内产生的ID计数已达上限，等待下一毫秒
                        timestamp = TillNextMilliseconds(LastTimestamp);
                    }
                }
                else
                {
                    //不同毫秒生成ID
                    Sequence = 0; //计数清0
                }
                if (timestamp < LastTimestamp)
                {
                    //如果当前时间戳比上一次生成ID时时间戳还小，抛出异常，因为不能保证现在生成的ID之前没有生成过
                    //throw new Exception(string.Format("Clock moved backwards.  Refusing to generate id for {0} milliseconds",
                    //    LastTimestamp - timestamp));
                    throw new System.Exception($"时钟向后移动。拒绝生成id {LastTimestamp - timestamp} 毫秒");
                }
                LastTimestamp = timestamp; //把当前时间戳保存为最后生成ID的时间戳
                long newId = timestamp - Twepoch << TimestampLeftShift | WorkerId << WorkerIdShift | Sequence;    // 移位并通过或运算拼到一起组成64位的ID
                return newId;
            }
        }
        #endregion

        #endregion

        #region "私有方法"
        #region "获取下一毫秒时间戳"
        /// <summary>
        /// 获取下一毫秒时间戳
        /// </summary>
        /// <param name="lastTimestamp">最后时间戳</param>
        /// <returns></returns>
        private static long TillNextMilliseconds(long lastTimestamp)
        {
            long timestamp = TimeGen();
            while (timestamp <= lastTimestamp)
            {
                timestamp = TimeGen();
            }
            return timestamp;
        }
        #endregion
        #region "生成当前时间戳(毫秒)"
        /// <summary>
        /// 生成当前时间戳(毫秒)
        /// </summary>
        /// <returns>当前时间(总毫秒数)</returns>
        private static long TimeGen()
        {
            return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
        }
        #endregion

        #endregion

    }

}
